angular.module('imsApp').controller('appDetailController', ['$scope', '$rootScope', '$state', 'AppManager', '$stateParams', 'ChannelsManager','$uibModal','$filter', function ($scope, $rootScope, $state, AppManager, $stateParams, ChannelsManager,$uibModal,$filter) {
     var appId=$stateParams.appId;
    var shortName = $stateParams.shortName;
    $scope.initData = {
        "codeTable": $scope.table,
        "initCode": {
            "appType": ["38", "39", "40", "41"],
            "targetTrade": ["101", "102", "103", "104", "105", "106", "107", "108", "109", "110", "111", "112", "113", "114", "115", "116", "117", "118", "119", "120", "121", "122", "123", "124", "125", "126", "127"],
            "targetAdType": ["81", "82", "83", "84"],
            "balanceType": ["25", "26", "27"],
        }
    };

    //ctrlData初始化方法
    var ctrlDataInit = function (data) {
        if (angular.isDefined(data)) {
            $scope.formData = data;
            $scope.formData.targetTrade = $filter("toArray")(data.targetTrade);
            $scope.formData.targetAdType = $filter("toArray")(data.targetAdType);
        } else {
            formDataInit();
        }
        if ($scope.planEdit) {
            $scope.ctrlData = {"targetTrade": 1, "targetAdType": 1};
        } else {
            $scope.ctrlData = {
                "targetTrade": $scope.formData.targetTrade != null ? $scope.formData.targetTrade.length ? 2 : 1 : 1,
                "targetAdType": $scope.formData.targetAdType != null ? $scope.formData.targetAdType.length ? 2 : 1 : 1,
            };
        }
    };

    //formData初始化方法
    var formDataInit = function () {
        $scope.formData = {
            "frequency": "5",
            "balanceType": "25",
            "appType": "38",
            "targetTrade": [],
            "targetAdType": []
        };
        $scope.planEdit = true;
    };

    //回写全选
    var backSelectAll = function () {
        $scope.halfData.targetTrade = $scope.formData.targetTrade.length == 0 ? false : ($scope.initData.initCode.targetTrade.length == $scope.formData.targetTrade.length) ? false : true;
        $scope.halfData.targetAdType = $scope.formData.targetAdType.length == 0 ? false : ($scope.initData.initCode.targetAdType.length == $scope.formData.targetAdType.length) ? false : true;

    };

    //获取详情成功回调方法
    var getDataSuccess = function (result) {
        if (result.c == "s") {
            ctrlDataInit(result.data);
            $stateParams.appId = result.data.appId;
            $scope.formData.frequency = $scope.formData.frequency.toString();
            $scope.ctrlData.shortName = shortName;
            $scope.title = result.title;
            $scope.uTime = result.uTime;
            backSelectAll();
        } else {
            alert(result.i);
        }
    };
    //获渠道成功
    var getChannelSuccess = function (result) {
        if (result.c == "s") {
            $scope.ctrlData.shortName = result.data.shortName;
            $scope.formData.channelId = $stateParams.channelId;
        } else {
            alert(result.i);
        }

    };
    //判断是否进入新建
    if (!$stateParams.appId) {//新建
        ctrlDataInit();
        if ($stateParams.channelId) {//通过渠道ID去查找shortName
            ChannelsManager.channelsDetail($stateParams.channelId).then(function (result) {
                getChannelSuccess(result.data);
            })
        }
    } else {
        AppManager.appDeatil($stateParams.appId).then(function (result) {
            getDataSuccess(result.data)
        })

    }

    //存全选结果的
    $scope.allName = [];
    //checkbox全选框初始化
    $scope.checboxAll = function (target, val) {
        return $scope.allName.indexOf(target.toString()) >= 0;
    };
    //全选
    $scope.selectAll = function ($event, target) {
        var checkbox = $event.target;
        var action = (checkbox.checked ? 'add' : 'remove');
        var allDex = $scope.allName.indexOf(target.toString());
        var str = target.toString();
        if (action == 'add') {
            $scope.halfData[target] = false;
            $scope.formData[target.toString()] = [];
            for (var i = 0; i < $scope.initData.initCode[str].length; i++) {
                $scope.formData[target.toString()].push($scope.initData.initCode[str][i]);
            }
            if (allDex == -1) {
                $scope.allName.push(str);
            }
        } else if (action == 'remove') {
            $scope.formData[str] = [];
            if (allDex != -1) {
                $scope.allName.splice(allDex, 1);
            }
        }
    };
    //定义部分选中
    $scope.halfData = {
        "targetAdType": false, "targetTrade": false
    };

    //checkbox数据添加删除方法
    var updateSelected = function (action, target, id) {
        if (action == 'add' && $scope.formData[target].indexOf(id) == -1) {
            $scope.formData[target].push(id);
            if ($scope.formData[target].length == $scope.initData.initCode[target].length) {
                var str = target.toString();
                if ($scope.allName.indexOf(str) == -1) {
                    $scope.allName.push(str);
                    $scope.halfData[target] = false;
                }
            } else {
                $scope.halfData[target] = true;
            }
        }
        if (action == 'remove' && $scope.formData[target].indexOf(id) != -1) {
            var idx = $scope.formData[target].indexOf(id);
            $scope.formData[target].splice(idx, 1);
            var allDex = $scope.allName.indexOf(target.toString());
            //全选时remove一个
            if (allDex != -1) {
                $scope.allName.splice(allDex, 1);
                $scope.halfData[target] = true;
            } else {
                //一个都没有选中了
                if ($scope.formData[target].length == 0) {
                    $scope.halfData[target] = false;
                } else {
                    $scope.halfData[target] = true;
                }
            }
        }
    };
    //checkbox数据添加删除方法
    $scope.updateSelection = function ($event, target, id) {
        var checkbox = $event.target;
        var action = (checkbox.checked ? 'add' : 'remove');
        updateSelected(action, target, id);
    };

    //checkbox选择初始化
    $scope.isSelected = function (target, id) {
        if (angular.isUndefined($scope.formData)) {
            return false;
        } else {
            return $scope.formData[target].indexOf(id) >= 0;
        }
    };

    //提交成功
    var submitSuccess = function (result) {
        $scope.planEdit = false;
        if ($stateParams.appId) {
            $state.go($state.current.name, {
                appId: $stateParams.appId,
                shortName: $scope.ctrlData.shortName
            }, {reload: true,inherit:false});
        } else {
            $state.go('app',{}, {reload: true,inherit:false});
        }
    };

    //提交
    $scope.submit = function () {
        var tpmToSave={};
        if ($scope.formData.channelId) {
            if ($scope.checkAppName() && $scope.checkPackageName()) {
                if ($scope.formData.price) {
                    $scope.formData.price = $scope.formData.price.toString();
                }
                $scope.formData.targetAdType = $scope.allName.indexOf("targetAdType") == -1 ? $scope.formData.targetAdType : "";
                $scope.formData.targetTrade = $scope.allName.indexOf("targetTrade") == -1 ? $scope.formData.targetTrade : "";

                for(var i in $scope.formData){
                    if($scope.formData[i] instanceof Array){
                        tpmToSave[i]=$scope.formData[i].join(",")
                    }else{
                        tpmToSave[i]=$scope.formData[i]
                    }
                }
                if(appId){
                    AppManager.appEdit(appId,tpmToSave).then(function (result) {

                        if(result.data.c=='s'){
                            submitSuccess(result.data);
                        }
                    })
                }else{
                    AppManager.appAdd(tpmToSave).then(function (result) {
                        if(result.data.c=='s'){
                            submitSuccess(result.data);
                        }
                    })
                }
            }
        } else {
            alert("请选择渠道主");
        }

    };
    //model参数配置
    $scope.modelChannelParam = {
        title: "渠道主选择",
        choose: function (selectedItem) {
            $scope.formData.channelId = selectedItem.channelId;
            $scope.ctrlData.shortName = selectedItem.shortName;
        }
    };
    //加载合约
    $scope.modelChannelContractIdParam = {
        title: "渠道合约",//初始参数
        url: "ims/loadChannelContractList.do",
        choose: function (selectedItem) {
            $scope.formData.contractId = selectedItem.id;//获取合约ID
        }

    };
    //model 点击打开。param：title文字、body数据、选择触发回调方法，size：model大小（big、small，默认中等大小）
    $scope.modelOpen = function (param, elm, size) {
        var modalInstance = $uibModal.open({
            templateUrl: 'myModalContent.html',
            controller: 'channelModalController',
            size: size,
            resolve: {
                param: param
            }
        });
        modalInstance.result.then(param.choose);
    };

    $scope.modelOpenChannelContract = function (param, elm, size) {
        if ($scope.formData.channelId) {
            param.key = "channelId";
            param.id = $scope.formData.channelId;
            var modalInstance = $uibModal.open({
                templateUrl: 'myContract.html',
                controller: 'channelContractsRelationModalController',
                size: size,
                resolve: {
                    param: param
                }
            });
            modalInstance.result.then(param.choose);
        } else {
            alert("请选择渠道主");
            return false;
        }
    };

    $scope.edit = function () {
        $scope.planEdit = true;
    };

    $scope.cancle = function () {
        if (!$stateParams.appId) {
            $state.go("app", {reload: true});
        } else {
            if ($scope.planEdit) {
                $state.reload();
            } else {
                $state.go("app", {reload: true});
            }
        }
    };

    //校验数据状态：1，r，e
    $scope.checkData = {"appName": '1', "appPackageName": '1'};
    //提示语信息
    $scope.hintData = {"appName": "", "appPackageName": ""};
    //校验应用名称
    $scope.checkAppName = function () {
        var name = $scope.formData.appName;
        if (name) {
            $scope.checkData.appName = "r";
            return true;
        } else {
            $scope.checkData.appName = "e";
            $scope.hintData.appName = "不能为空";
            return false;
        }
    };
    //校验包名
    $scope.checkPackageName = function () {
        var name = $scope.formData.appPackageName;
        if (name) {
            var reg = /^[0-9a-zA-Z._]+$/;
            if (reg.test(name)) {
                $scope.checkData.appPackageName = "r";
                return true;
            } else {
                $scope.checkData.appPackageName = "e";
                $scope.hintData.appPackageName = "只能含有数字、字母、下划线、小数点";
                return false;
            }

        } else {
            $scope.checkData.appPackageName = "e";
            $scope.hintData.appPackageName = "不能为空";
            return false;
        }
    };


}])

